// @ts-ignore
import classNames from 'classnames'
import Taro, {Component} from '@tarojs/taro'
import {View, Image, Button} from '@tarojs/components'
import './index.scss'

interface IProps {
  width: number // 分享图宽度
  height: number // 分享图高度
  image: string //  分享图片
  isOpened: boolean //  显示隐藏
  onClose: Function //  取消事件
}

export default class ShareImage extends Component<IProps, {}> {
  state: any
  props: any
  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
  }

  onClear(e) {
    e.stopPropagation()
  }

  //  查看图片
  handlePreviewImage (image, e) {
    e.stopPropagation()
    wx.previewImage({
      current: image,
      urls: [image]
    })
  }

  //  保存图片到相册
  handleSaveImage (image) {
    wx.showLoading({title: '保存中...'})
    wx.downloadFile({
      url: image,
      success (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success () {
            wx.hideLoading()
            wx.showToast({title: '保存成功'})
            Taro.removeSavedFile({ filePath: res.tempFilePath })
          },
          fail (err) {
            wx.hideLoading()
            wx.showToast({icon: 'none', title: err.errMsg})
          }
        })
      },
      fail () {
        wx.hideLoading()
        wx.showToast({ icon: 'none', title: '下载失败' })
      }
    })
  }

  render() {
    const {width, height, image, isOpened, onClose} = this.props
    // @ts-ignore
    return (<View className='share-image-modal' catchtouchmove>
      {<View className={classNames('mask-class fy-transition fade fy-mask', isOpened && 'show')} onClick={() => onClose()}/>}
      {<View className={classNames('trans-class fy-transition slide-bottom fy-full', isOpened && 'show')}  onClick={() => onClose()}>
        <View className='share-image' onClick={this.onClear.bind(this)}>
          {image && <Image src={image} className='image' style={`width: ${width}rpx;height: ${height}rpx;`} onClick={this.handlePreviewImage.bind(this, image)}/>}
          {!image && <View className='share-loading'>
              <View className='bnn-icon load-icon'>&#xe636;</View>
              <View className='load-text'>生成海报中</View>
          </View>}
        </View>
        <View className='share-bottom fy-popup fy-popup--bottom fy-popup--round' onClick={this.onClear.bind(this)}>
          <Button openType='share' className='share-btn d-f f-d-c a-i-c j-c-c'>
            <View className='bnn-icon btn-icon'>&#xe62f;</View>
            <View className='btn-text'>分享好友</View>
          </Button>
          <Button className='share-btn d-f f-d-c a-i-c j-c-c' onClick={this.handleSaveImage.bind(this, image)}>
            <View className='bnn-icon btn-icon'>&#xe60b;</View>
            <View className='btn-text'>保存海报</View>
          </Button>
        </View>
      </View>}
    </View>)
  }
}
